//
//  FYFMainViewController.m
//  TipNavigation
//
//  Created by fuyoufang on 16/2/21.
//  Copyright © 2016年 fyf. All rights reserved.
//

#import "FYFMainViewController.h"
#import "FYFTitleLabel.h"
#import "FYFContentViewController.h"

#define FYFScreenWidth [UIScreen mainScreen].bounds.size.width
/** 标题栏的高度 */
#define FYFTitlesScrollViewHeight 40
#define FYFTitlesScrollViewMargin 4
/** title 背景比 title 左边大的距离 */
#define FYFTitleLabelLeftMargin 6
/** title 背景比 title 右边大的距离 */
#define FYFTitleLabelRightMargin FYFTitleLabelLeftMargin
/** title 背景比 title 上边大距离 */
#define FYFTitleLabelTopMargin 5
/** title 背景比 title 下边大的距离 */
#define FYFTitleLabelBottomMargin FYFTitleLabelTopMargin

@interface FYFMainViewController () <UIScrollViewDelegate>

@property (nonatomic, weak) UIScrollView *titlesScrollView;
@property (nonatomic, weak) UIImageView *titleBackgroundImageView;
@property (nonatomic, weak) UIScrollView *contentsScrollView;
@property (nonatomic, strong) NSMutableArray *contentControllers;

@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSMutableArray *titleLabels;
@property (nonatomic, strong) NSMutableArray *titleBackgroundImageViewFrames;
@end

@implementation FYFMainViewController

#pragma mark - 懒加载

- (NSMutableArray *)contentControllers {
    if (_contentControllers == nil) {
        _contentControllers = [NSMutableArray array];
    }
    return _contentControllers;
}

- (NSMutableArray *)titleBackgroundImageViewFrames {
    if (_titleBackgroundImageViewFrames == nil) {
        _titleBackgroundImageViewFrames = [NSMutableArray array];
    }
    return _titleBackgroundImageViewFrames;
}

- (NSMutableArray *)titleLabels {
    if (_titleLabels == nil) {
        _titleLabels = [NSMutableArray array];
    }
    return _titleLabels;
}

- (NSArray *)titles{
    if (_titles == nil) {
        _titles = @[@"China", @"United States", @"Germany", @"Japan", @"English"];
    }
    return _titles;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //
    [self setupSubviews];
    
    //
    [self setupContents];
}

- (void)setupSubviews {
    UIScrollView *titlesScrollView = [[UIScrollView alloc] init];
    titlesScrollView.translatesAutoresizingMaskIntoConstraints = NO;
    titlesScrollView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:titlesScrollView];
    self.titlesScrollView = titlesScrollView;
    
    UIScrollView *contentsScrollview = [[UIScrollView alloc] init];
    contentsScrollview.translatesAutoresizingMaskIntoConstraints = NO;
    contentsScrollview.backgroundColor = [UIColor grayColor];
    contentsScrollview.pagingEnabled = YES;
    contentsScrollview.delegate = self;
    [self.view addSubview:contentsScrollview];
    self.contentsScrollView = contentsScrollview;
    
    UIImageView *titleBackgroundImageView= [[UIImageView alloc] init];
    titleBackgroundImageView.backgroundColor = [UIColor greenColor];
    [self.titlesScrollView addSubview:titleBackgroundImageView];
    self.titleBackgroundImageView = titleBackgroundImageView;
    
    // 设置约束
    NSDictionary *subviews = NSDictionaryOfVariableBindings(titlesScrollView, contentsScrollview);
    NSDictionary *metrics = @{
                              @"titlesScrollViewHeight" : @(FYFTitlesScrollViewHeight)};
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(64)-[titlesScrollView(titlesScrollViewHeight)][contentsScrollview]|" options:0 metrics:metrics views:subviews]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[titlesScrollView]|" options:0 metrics:nil views:subviews]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentsScrollview]|" options:0 metrics:nil views:subviews]];
    
}

- (void)setupContents {
    // 设置 titlesScrollView
    CGFloat labelX = FYFTitlesScrollViewMargin;
    //CGFloat contentViewX = 0;
    NSInteger index = 0;
    UIFont *titleFont = [UIFont systemFontOfSize:30];
    NSDictionary *titleAttributes = @{NSFontAttributeName : titleFont};
    CGSize titleMaxSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
    for (NSString *title in self.titles) {
        // 添加 title
        CGRect labelFrame = [title boundingRectWithSize:titleMaxSize options:0 attributes:titleAttributes context:nil];
        labelFrame.size.width += (FYFTitleLabelLeftMargin + FYFTitleLabelRightMargin);
        labelFrame.origin.x = labelX;
        labelFrame.origin.y = FYFTitleLabelTopMargin;
        labelFrame.size.height = FYFTitlesScrollViewHeight - FYFTitleLabelTopMargin - FYFTitleLabelBottomMargin;
        FYFTitleLabel *label = [FYFTitleLabel labelWithTitle:title index:index];
        label.frame = labelFrame;
        label.font = titleFont;
        label.userInteractionEnabled = YES;
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelSelected:)]];
        [self.titlesScrollView addSubview:label];
        NSValue *labelFrameValue = [NSValue valueWithCGRect:labelFrame];
        
        labelX += labelFrame.size.width;
        [self.titleLabels addObject:label];

        // 设置背景
        CGRect titleBackgroundImageViewFrame = labelFrame;
        [self.titleBackgroundImageViewFrames addObject:labelFrameValue];
        if (index == 0) {
            self.titleBackgroundImageView.frame = titleBackgroundImageViewFrame;
        }

        // 添加 controller
        FYFContentViewController *controller = [[FYFContentViewController alloc] init];
        [self addChildViewController:controller];
        [self.contentControllers addObject:controller];
        
        index++;
    }
    labelX += FYFTitlesScrollViewMargin;
    self.titlesScrollView.contentSize = CGSizeMake(labelX, 0);
    self.contentsScrollView.contentSize = CGSizeMake(index * FYFScreenWidth, 0);
    
}

/**
 *  typeLabel 点击事件
 */
- (void)titleLabelSelected:(UITapGestureRecognizer *)recognizer {
    FYFTitleLabel *titleLabel = (FYFTitleLabel *)recognizer.view;
    
    CGFloat offsetX = titleLabel.index * self.contentsScrollView.frame.size.width;
    CGFloat offsetY = self.contentsScrollView.contentOffset.y;
    CGPoint offset = CGPointMake(offsetX, offsetY);
    
    [self.contentsScrollView setContentOffset:offset animated:YES];

}

#pragma mark - UIScrollViewDelegate
/** 
 *  滚动结束后调用（代码导致的滚动）
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (scrollView == self.contentsScrollView) {
        // 获取索引
        NSInteger index = scrollView.contentOffset.x / FYFScreenWidth;
        
        // 滚动标题栏
        FYFTitleLabel *titleLable = (FYFTitleLabel *)self.titleLabels[index];
        CGFloat offsetX = titleLable.center.x - self.titlesScrollView.frame.size.width * 0.5;
        CGFloat offsetMax = self.titlesScrollView.contentSize.width - self.titlesScrollView.frame.size.width;
        if (offsetX < 0) {
            offsetX = 0;
        } else if (offsetX > offsetMax){
            offsetX = offsetMax;
        }
        CGPoint offset = CGPointMake(offsetX, self.titlesScrollView.contentOffset.y);
        [self.titlesScrollView setContentOffset:offset animated:YES];
        
        // 添加控制器
        FYFContentViewController *contentVC = self.contentControllers[index];
        if (contentVC.view.superview) return;
        
        contentVC.view.frame = scrollView.bounds;
        [self.contentsScrollView addSubview:contentVC.view];
    }
}

/** 滚动结束（手势导致） */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.contentsScrollView) {
        // 取出绝对值 避免最左边往右拉时形变超过1
        CGFloat value = scrollView.contentOffset.x / scrollView.bounds.size.width;
        if (value < 0) {
            return;
        }
        // 获取索引
        NSInteger leftIndex = (NSInteger)value;
        NSInteger rightIndex = leftIndex + 1;
        FYFTitleLabel *leftTitleLabel = self.titleLabels[leftIndex];
        CGFloat scale = value - leftIndex;
        leftTitleLabel.scale = (1 - scale);
        if (rightIndex < self.titleLabels.count) {
            FYFTitleLabel *rightTitleLabel = self.titleLabels[rightIndex];
            rightTitleLabel.scale = scale;
            
            // 设置 title 的背景图片
            CGRect leftLabelFrame = [self.titleBackgroundImageViewFrames[leftIndex] CGRectValue];
            CGRect rightLabelFrame = [self.titleBackgroundImageViewFrames[rightIndex] CGRectValue];
            CGRect titleBackgroundImageViewFrame = self.titleBackgroundImageView.frame;
            titleBackgroundImageViewFrame.origin.x =
            leftLabelFrame.origin.x + (rightLabelFrame.origin.x - leftLabelFrame.origin.x) * scale;
            titleBackgroundImageViewFrame.size.width =
            leftLabelFrame.size.width + (rightLabelFrame.size.width - leftLabelFrame.size.width) * scale;
            self.titleBackgroundImageView.frame = titleBackgroundImageViewFrame;
        }
    }
}
                                 


@end
